package ArrayList;

public class ArrayList<E> {
    private int size = 0;
    private int capacity = 10;
    private Object[] arr = new Object[capacity];

    public void add(E element, int index) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("位置非法");
        }

        if (size >= capacity) {
            int newCapacity = capacity + (capacity >> 1);
            Object[] newArr = new Object[newCapacity];
            System.arraycopy(arr, 0, newArr, 0, size);
            arr = newArr;
            capacity = newCapacity;
        }

        for (int i = size; i > index; i--) {
            arr[i] = arr[i - 1];
        }

        arr[index] = element;
        size++;
    }

    public E remove(int index) {
        E e = (E) arr[index];
        if (index < 0 || index > size - 1) {
            throw new IndexOutOfBoundsException("非法");
        }
        for (int i = index; i < size; i++) {
            arr[i] = arr[i + 1];
        }
        size--;
        return e;
    }

    public E get(int index) {
        if (index < 0 || index > size - 1) {
            throw new IndexOutOfBoundsException("非法");
        }
        return (E) arr[index];
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            sb.append(arr[i]).append(" ");
        }
        return sb.toString();
    }
}
